package com.purchase.manage.service.impl;

import com.purchase.common.utils.SecurityUtils;
import com.purchase.common.utils.uuid.IdUtils;
import com.purchase.manage.damian.Purchase;
import com.purchase.manage.mapper.ManagePurchaseMapper;
import com.purchase.manage.service.IManagePurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author oyi46
 * @version 1.0
 * Create by 2023/7/3 14:38
 */

@Service
public class ManagePurchaseServiceImpl implements IManagePurchaseService {

    @Autowired
    ManagePurchaseMapper managePurchaseMapper;

    //采购员注册前判断是否重复
    @Override
    public boolean checkUser(Purchase purchase) {
        return managePurchaseMapper.checkUser(purchase) == 0;
    }

    //采购员注册
    @Override
    @Transactional
    public int addPurchase(Purchase purchase) {
        purchase.setPassword(SecurityUtils.encryptPassword(purchase.getPassword())); //密码加密
        String pid = String.valueOf(IdUtils.randomSnowflake());
        purchase.setPurchaseId(pid);
        if (managePurchaseMapper.selectCount(purchase.getPhone()) !=0){
            return 0;
        }
        managePurchaseMapper.insertSysUser(purchase);   //添加进用户表
        String userid = managePurchaseMapper.selectUser(purchase);
        managePurchaseMapper.insertRoleUser(userid);    //添加进权限表
        managePurchaseMapper.insertSysUserPurchase(userid, pid);   //添加进用户和采购员关系表
        managePurchaseMapper.insertPurchase(purchase);  //添加进采购员表
        return 1;
    }

    //修改采购员信息
    @Override
    @Transactional
    public void updatePurchase(Purchase purchase) {

        Purchase pur = managePurchaseMapper.selectPurchase(purchase.getPurchaseId());
        //检测是否存在
        if (pur == null){
            throw new SecurityException("该采购员不存在");
        }
        //修改信息
        if (managePurchaseMapper.updatePurchase(purchase) !=1){
            throw new SecurityException("修改采购员'" + purchase.getName() + "信息失败");
        }
        purchase.setPassword(SecurityUtils.encryptPassword(purchase.getPassword()));
        //修改密码
        managePurchaseMapper.updatePassword(purchase);
    }
}
